package com.yj.web.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
 * Created with IntelliJ IDEA.
 * Employee: yesiming
 * Date: 13-11-4
 * Time: 下午3:15
 * To change this template use File | Settings | File Templates.
 */
public class WebUtils {

    private static final Log logger = LogFactory.getLog(WebUtils.class);

    public static Gson GSON = new GsonBuilder()
            .disableHtmlEscaping()
            .registerTypeAdapter(Date.class, new WebUtils.DateDeserializer())
            .registerTypeAdapter(Date.class, new WebUtils.DateSerializer())
            .setDateFormat(DateFormat.LONG).create();

    private static Pattern emailCheckPatten = Pattern.compile("[\\w\\.\\-]+@[\\w\\.\\-]+");

    private static Pattern fuzzCheckPhonePatten = Pattern.compile("[\\+\\-\\(\\) 0-9]+");

    private static Pattern originURLPatten = Pattern.compile("(http|https)://[0-9A-Za-z_\\.\\-]*quadapp\\.com.*");

    public static int getHostId(HttpServletRequest request) {
        Integer hostId = (Integer) request.getAttribute("hostId");
        if (hostId == null) {
            return 0;
        }
        return hostId;
    }
    /**
     * 输出Web的ajax结果
     *
     * @param out
     * @param rt
     */
    public static String ajaxOutput(PrintWriter out, BaseWebResult rt) {
        out.print(webResultToJSON(rt));
        out.flush();
        // 返回必须为null
        return null;
    }

    /**
     * 把web返回的bean转成json
     *
     * @param rt
     * @return
     */
    public static String webResultToJSON(BaseWebResult rt) {
        return GSON.toJson(rt == null ? "{}" : fillWebResult(rt));
    }
    
    /**
     * 根据errorcode填充errormsg
     *
     * @param rt
     * @return
     */
    private static BaseWebResult fillWebResult(BaseWebResult rt) {
        if (rt == null || rt.getCd() == 0) {
            return rt;
        }
        rt.setMsg(ConfigUtils.getMsgByErrorCode(rt.getCd()));
        return rt;
    }
    
    /**
     * 获得页面的输出，用来ajax输出
     *
     * @param response
     * @return
     */
    public static PrintWriter getAjaxWriter(HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            logger.error("", e);
        }
        return out;
    }
    
    public static class DateDeserializer implements JsonDeserializer<Date> {

        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
        }
    }
    
    public static class DateSerializer implements JsonSerializer<Date> {
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.getTime());
        }
    }
}
